<template>
  <div class="newslist-container">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        :offset="300"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <router-link
          tag="div"
          :to="'/NewDetail/' + item.id"
          class="item"
          v-for="item in newList"
          :key="item.id"
        >
          <div class="imgWrap">
            <img v-lazy="item.img_url" />
          </div>
          <div class="info">
            <div class="title van-multi-ellipsis--l2">{{ item.title }}</div>
            <div class="date">
              <span
                >日期：{{ item.add_time | datatime("YYYY-MM-DD hh:mm") }}</span
              >
              <span>浏览次数：{{ item.click }}</span>
            </div>
          </div>
        </router-link>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { fetchNews } from "@/api/index.js";
export default {
  data() {
    return {
      page: 0,
      limit: 4,
      newList: [],
      loading: false, // 控制是否在加载中
      finished: false, // 控制是否加载完成
      refreshing: false, // 控制是否在刷新中...
    };
  },
  created() {},
  methods: {
    async _fetchNews() {
      //   正在刷新中则把数据清空
      if (this.refreshing) {
        this.newList = [];
        this.refreshing = false;
      }
      let { message } = await fetchNews(this.page, this.limit);
      this.newList = [...this.newList, ...message];
      this.loading = false; // 加载完毕

      if (message.length === 0) {
        this.finished = true;
      }
    },
    handle(data, event) {
      this.$router.push("/newsdetail/" + data.id);
    },
    onLoad() {
      console.log("默认onLoad会加载一次");
      this.page++;
      // 默认会加载一次
      this._fetchNews();
    },
    onRefresh() {
      console.log("onRefresh刷新");
      this.page = 0;
      // 清空列表数据
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
  },
};
</script>

<style lang="scss" scoped>
.newslist-container {
  .item {
    display: flex;
    justify-content: space-between;
    padding: 4px;
    .imgWrap {
      width: 100px;
      height: 100px;
      margin: 4px;

      img {
        width: 100px;
        height: 100%;
      }
    }

    .info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .title {
        font-weight: 700;
        padding: 6px 0;
      }

      .date {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #b19eab;
      }
    }
  }
}
</style>

